# 按下btn让led变亮直到最亮, 抬起保持亮度, 再按下变暗直到不亮
# pin 11:G17 button
# pin 12:G18 red led
# pin 13:G27 green led
import RPi.GPIO as GP
import time

pin_green = 13
pin_btn = 11
pin_red = 12
p_red = None

def start():
    GP.setmode(GP.BOARD)
    GP.setwarnings(False)
    GP.setup(pin_btn, GP.IN,pull_up_down=GP.PUD_UP)
    GP.setup(pin_red, GP.OUT)
    
def loop():
    # 变亮标记
    turn_light = True
    # 亮度值(占空比))
    ligthen = 0
    change = True
    p_red = GP.PWM(pin_red,200)
    p_red.start(ligthen)
    while True:
        if not GP.input(pin_btn) and change: # 按下状态
            turn_light = not turn_light
            change = False
        else:
            change = True
        # print(turn_light)

        if turn_light and ligthen<100:
            ligthen+=1
            time.sleep(0.1)
        elif not turn_light and ligthen>0:
            ligthen-=1
            time.sleep(0.1)
        p_red.ChangeDutyCycle(ligthen)
        print(ligthen)
def close():
    p_red.ChangeDutyCycle(0)
    p_red.stop()
    # GP.output(pin_red,0)
    GP.cleanup()


if __name__ == '__main__':
    start()
    try:
        loop()
    except Exception as e:
        print(e)
        close()

